package cn.itsource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import cn.itsource.bean.Employee;
import cn.itsource.bean.LoginInfo;
import cn.itsource.config.PageList;
import cn.itsource.expection.BusinessException;
import cn.itsource.mapper.EmployeeMapper;
import cn.itsource.query.EmpQuery;
import cn.itsource.service.IEmployeeService;
import cn.itsource.service.IShopService;
import cn.itsource.util.JsonResult;
import cn.itsource.util.Md5Password;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.itsource.util.RedisContants.*;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-08 10:44:00
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Resource
    private IShopService shopService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult getPage(EmpQuery query) {
        //1.获取条件
        String key = query.getKeyword();
        //2.获取原始分页
        Page<Employee> pageKey = new Page<>(query.getPage(),query.getRows());

        //查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(key),Employee::getUsername,key);
        Page<Employee> page = this.page(pageKey, queryWrapper);

        //将获取的条件取出
        List<Employee> records = page.getRecords();
        long total = page.getTotal();
        PageList<Employee> pageList = new PageList<>();
        pageList.setTotal(total);
        pageList.setList(records);


        return JsonResult.success(pageList);
    }


    /**
     * 员工登入方法
     * @param employee
     * @return
     */
    @Override
    public JsonResult login(Employee employee) {
        //获取到雇员username,数据库查询对应的员工信息
        String username = employee.getUsername();
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,username);
        queryWrapper.or().eq(Employee::getEmail,username);
        queryWrapper.or().eq(Employee::getPhone,username);
        Employee empMgs = this.getOne(queryWrapper);
        //判断是否存在
        if (empMgs==null){
            throw new BusinessException("账号和密码不匹配");
        }
        //将传进来的密码加盐加密
        String md5Password = Md5Password.getMd5Password(employee.getPassword(), empMgs.getSalt());
        //查询对应的员工信息后将前端传输的密码做比对
        String sqlPassword = empMgs.getPassword();
        if (!md5Password.equals(sqlPassword)){
            //若不相等，抛出异常
            throw new BusinessException("账号和密码不匹配2");
        }

        //若账号和密码都正确，则生成token令牌
        //生成一个token，作为登入令牌               true带下划线的UUID
        String token = UUID.randomUUID().toString(true);


        //将雇员对象转换为json存储
        LoginInfo loginInfo = BeanUtil.copyProperties(empMgs,LoginInfo.class);
        String jsonEmp = JSONUtil.toJsonStr(loginInfo);

        // 员工登入key
        String key = LOGIN_USER_KEY + token;

        //存储和设置有效期 360分钟
        stringRedisTemplate.opsForValue().set(key,jsonEmp,LOGIN_EMP_TTL,TimeUnit.MINUTES);

        loginInfo.setToken(token);
        //返回
        return JsonResult.success(loginInfo);
    }

    @Override
    public JsonResult getEmp(Long id) {
        if (id==null){
            return JsonResult.error("信息错误");
        }

        //获取以该id为上级以及该id的员工信息
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getId,id).or()
        .eq(Employee::getManagerId,id);


        List<Employee> list = this.list(queryWrapper);



        return JsonResult.success(list);
    }
}
